package com.scqkxx.gamebox.activity.myself;

import android.graphics.Color;
import android.os.CountDownTimer;
import android.view.KeyEvent;
import android.view.View;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.LogInCallback;
import com.scqkxx.gamebox.R;
import com.scqkxx.gamebox.activity.myself.loginutils.InputVerificationUtils;
import com.scqkxx.gamebox.activity.myself.loginutils.LoginRequestUtils;
import com.scqkxx.gamebox.activity.myself.loginutils.OnRequestListener;
import com.scqkxx.gamebox.activity.webview.web.WebViewActivity;
import com.scqkxx.gamebox.activity.webview.web.model.WebViewConfig;
import com.scqkxx.gamebox.databinding.ActivityRegisteredBinding;
import com.scqkzqtz.base.base.BaseActivity;
import com.scqkzqtz.base.event.LoginEvent;
import com.scqkzqtz.base.library.utils.DrawableUtil;
import com.scqkzqtz.base.library.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;

import io.reactivex.disposables.Disposable;

/**
 * Created by zsx on 2018/8/14.
 */

public class RegisteredActivity extends BaseActivity<ActivityRegisteredBinding> {
    private CountDownTimer countDownTimer;

    @Override
    public int setLayoutId() {
        return R.layout.activity_registered;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    @Override
    public void init() {
        initCode();
        initRegistered();

        binding.mTitleView.setOnTitleClickListener((int mTitleType) -> {
            if (binding.linlayPhone.getVisibility() == View.VISIBLE) {
                finish();
            } else {
                binding.linlayPhone.setVisibility(View.VISIBLE);
                binding.linlayRegistered.setVisibility(View.GONE);
            }
        });
    }

    private void initRegistered() {
        binding.linlayPhone.setVisibility(View.VISIBLE);
        binding.linlayRegistered.setVisibility(View.GONE);

        binding.linlayCode.setBackground(DrawableUtil.getSolidRectDrawable(4, Color.parseColor("#F3F3F3")));
        binding.linlayPassword.setBackground(DrawableUtil.getSolidRectDrawable(4, Color.parseColor("#F3F3F3")));
        binding.tvNext.setBackground(DrawableUtil.getSolidRectDrawable(4, Color.parseColor("#DBDBDB")));
        binding.tvRegistered.setBackground(DrawableUtil.getSolidRectDrawable(4, Color.parseColor("#DBDBDB")));

        binding.etCode.setTag(InputVerificationUtils.TAG_SMSCODE);
        binding.etPassword.setTag(InputVerificationUtils.TAG_PASSWORD);
        InputVerificationUtils.onPutListener(binding.tvRegistered, binding.etCode, binding.etPassword);
        InputVerificationUtils.psdShowHide(binding.checkboxPassword, binding.etPassword);

        binding.tvProtocol.setOnClickListener(v -> {
            WebViewConfig webViewConfig = new WebViewConfig("file:///android_asset/user_contract.html")
                    .isShowProgressBar(false)
                    .isShowCollection(false)
                    .isFontScaling(false)
                    .setBuiltInZoomControls(false)
                    .setTitle(getResources().getString(R.string.uc_title));
            startActivity(WebViewActivity.getIntent(this,webViewConfig));
        });

        binding.tvGetCode.setOnClickListener(v -> {
            if ("获取验证码".equals(binding.tvGetCode.getText().toString())) {
                requestSmsCode();
            }
        });

        binding.tvRegistered.setOnClickListener(v -> {
            if (!binding.checkbox.isChecked()) {
                ToastUtils.showShortToast(this, RegisteredActivity.this.getResources().getString(R.string.registered_protocol));
                return;
            }
            if (InputVerificationUtils.isPutMeet(binding.etCode, binding.etPassword)) {
                LoginRequestUtils.registerBySmsCode(this, binding.etCode.getText().toString().trim(),
                        binding.etPhoneNumber.getText().toString().trim(),
                        binding.etPassword.getText().toString().trim(), new OnRequestListener() {
                            @Override
                            public void OnVerificationSuccess() {
                                binding.tvRegistered.setEnabled(false);
                            }

                            @Override
                            public void OnVerificationError(String s) {
                                ToastUtils.showShortToast(RegisteredActivity.this, s);
                                binding.tvRegistered.setEnabled(true);
                            }

                            @Override
                            public void OnSuccer(Map<String, Object> map) {
                                binding.tvRegistered.setEnabled(true);
                                EventBus.getDefault().post(new LoginEvent(LoginEvent.TAG_REGISTER));
                                try {
                                    Map<String, Object> mapData = (Map<String, Object>) map.get("data");
                                    String sessionToken = mapData.get("sessionToken") + "";
                                    AVUser.becomeWithSessionTokenInBackground(sessionToken, new LogInCallback<AVUser>() {
                                        @Override
                                        public void done(AVUser user, AVException e) {
                                            if (e == null) {
                                                ToastUtils.showShortToast(RegisteredActivity.this, RegisteredActivity.this.getResources().getString(R.string.registered_success));
                                                RegisteredActivity.this.finish();
                                            }
                                        }
                                    });
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void OnError(String s) {
                                binding.tvRegistered.setEnabled(true);
                                ToastUtils.showShortToast(RegisteredActivity.this, s);
                            }

                            @Override
                            public void onSubscribe(Disposable d) {
                                addDisposable(d);
                            }
                        });
            }
        });
    }

    private void initCode() {
        binding.etPhoneNumber.setBackground(DrawableUtil.getSolidRectDrawable(4, Color.parseColor("#F3F3F3")));
        binding.tvNext.setOnClickListener(v -> {
            requestSmsCode();
        });

        binding.etPhoneNumber.setTag(InputVerificationUtils.TAG_PHONENUMBER);
        InputVerificationUtils.onPutListener(binding.tvNext, binding.etPhoneNumber);
    }

    private void requestSmsCode() {
        if (InputVerificationUtils.isPutMeet(binding.etPhoneNumber)) {
            LoginRequestUtils.requestSmsCode(this, LoginRequestUtils.SMSTYPE_LOGIN, binding.etPhoneNumber.getText().toString().trim(), new OnRequestListener() {
                @Override
                public void OnVerificationSuccess() {
                    binding.linlayPhone.setVisibility(View.GONE);
                    binding.linlayRegistered.setVisibility(View.VISIBLE);
                    binding.etCode.setText("");
                    binding.etPassword.setText("");
                    binding.etCode.setFocusable(true);
                    binding.etCode.setFocusableInTouchMode(true);
                    binding.etCode.requestFocus();
                    countDownTimer = new CountDownTimer(60 * 1000, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            binding.tvGetCode.setText("重新发送" + millisUntilFinished / 1000);
                            binding.tvGetCode.setTextColor(Color.parseColor("#E6A516"));
                        }

                        @Override
                        public void onFinish() {
                            binding.tvGetCode.setText("获取验证码");
                            binding.tvGetCode.setTextColor(Color.parseColor("#333333"));
                        }
                    }.start();
                }

                @Override
                public void OnVerificationError(String s) {
                    ToastUtils.showShortToast(RegisteredActivity.this, s);
                }

                @Override
                public void OnSuccer(Map<String, Object> map) {

                }

                @Override
                public void OnError(String s) {
                    countDownTimer.cancel();
                    ToastUtils.showShortToast(RegisteredActivity.this, s);
                    binding.tvGetCode.setText("获取验证码");
                    binding.tvGetCode.setTextColor(Color.parseColor("#333333"));
                }

                @Override
                public void onSubscribe(Disposable d) {
                    addDisposable(d);
                }
            });
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (binding.linlayPhone.getVisibility() == View.VISIBLE) {
                finish();
            } else {
                binding.linlayPhone.setVisibility(View.VISIBLE);
                binding.linlayRegistered.setVisibility(View.GONE);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
